package org.sg20.graphbuilder;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.sg20.utils.Edge;
import org.sg20.utils.ParseText;

import java.io.IOException;
import java.util.HashSet;

public class GraphBuilderMapper extends Mapper<LongWritable, Text, Text, Text> {

    //Text PR_init;
    Text out_key;
    Text out_val;

    private static HashSet<String> characters = new HashSet<String>();

    public static int getCharacterSize(){
        return characters.size();
    }

    @Override
    protected void setup(Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException{
        //PR_init = new Text("1.0");
        out_key = new Text();
        out_val = new Text();
    }


    /*
    由任务3的输出得到格式为 唐僧 [悟空,0.5|八戒,0.5]
     */
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context) throws IOException, InterruptedException {
        String[] thisInput = value.toString().split("\t");
        Edge[] edges= ParseText.parseEdges(thisInput[1]);
        out_key.set(thisInput[0]);
        characters.add(thisInput[0]);
        String val = "";
        for(Edge edge : edges){
            val +=  edge.getDestName() + "*" + String.valueOf(edge.getWeight());
            val += ",";
        }
        //out_val.set(String.format("%s|%s",PR_init, val));
        out_val.set(val);
        /*
        former   输出为 唐僧 1.0|悟空,八戒
        latter   输出为 唐僧 悟空*0.5,八戒*0.5
         */
        context.write(out_key, out_val);
    }
}
